<?PHP
  class Dashboard extends Editor{
    public $cols;
    public $usedwidgets = null;

    /**
     * @return string
     */
    public function getHeader(){
      $host = Settings::getInstance()->get("host");
      return "<link href=\"".$host."admin/style.css\" rel=\"stylesheet\" type=\"text/css\" />
              <link href=\"".$host."admin/inettuts.css\" rel=\"stylesheet\" type=\"text/css\" />
              <script type=\"text/javascript\" src=\"".$host."admin/inettuts.js\"></script>";
    }
    
    /**
     *
     * @param Page $page 
     */
    function __construct(Page $page){
      $this->page = $page;
      if(!$page->loadforbeadrcumb){
        $this->loadAllWidgets();
      }
    }

    private function loadAllWidgets(){
      $this->cols = null;
      $this->cols[] = $this->loadWidgetsByColumn(0);
      $this->cols[] = $this->loadWidgetsByColumn(1);
      $this->cols[] = $this->loadWidgetsByColumn(2);
      $this->cols[] = $this->loadWidgetsByColumn(3);  
    }
    
    /**
     *
     * @param int $columnId
     * @return array 
     */
    function loadWidgetsByColumn($columnId){
      $res = null;
      $columnId = DataBase::Current()->EscapeString($columnId);
      $alias = DataBase::Current()->EscapeString($this->page->alias);
      $rows = DataBase::Current()->ReadRows("SELECT path FROM {'dbprefix'}dashboards 
                                        WHERE col = '".$columnId."' AND alias = '".$alias."'
                                           ORDER BY row");
      if($rows){
        foreach($rows as $row){
          $widgetData = WidgetController::getWidgetData($row->path);
          $widget = WidgetController::getWidget($widgetData);
          if($widget){
            $widget->load();
            $res[] = $widget;
          }
        }
      }
      
      return $res;
    }
    
    function display(){
      $host = Settings::getInstance()->get("host");
      $template = new Template();
      $template->load("dashboard");
      $template->assign_var("COLUMNS", $this->getColumnsCode());
      $template->output();
    }

    /**
     *
     * @return string
     */
    private function getColumnsCode(){
      return  $this->getColumnCode(1).$this->getColumnCode(2).$this->getColumnCode(3);
    }
    
    /**
     *
     * @return string 
     */
    public function getEditableCode(){
      $template = new Template();
      $template->load("control_dashboardedit");
      $template->assign_var("URL",$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
      if($_POST['save']){
        $this->delete();
        $allwidgets = WidgetController::getAllWidgets();
        foreach($allwidgets as $widget){
          if(isset($_POST[str_replace(".","_",$widget->path)])){
            $widget->load();
            $parts = split("\|",$_POST[str_replace(".","_",$widget->path)]);
            if($parts[0] == "HIDDENWIDGETS"){
              $widget->save($this->page->alias,0,$parts[1]);
            }
            else if($parts[0] == "COLUMN1WIDGETS"){
              $widget->save($this->page->alias,1,$parts[1]);
            }
            else if($parts[0] == "COLUMN2WIDGETS"){
              $widget->save($this->page->alias,2,$parts[1]);
            }
            else if($parts[0] == "COLUMN3WIDGETS"){
              $widget->save($this->page->alias,3,$parts[1]);
            }
          }
        }
        $this->loadAllWidgets();
      }
      if(isset($allwidgets)){
        foreach($allwidgets as $widget){
          $widget->load();
        }
      }
      $i = 0;
      $pos = 0;
      foreach($this->cols as $col){
        if($col && $i != 0){
          foreach($col as $widget){
            $index = $template->add_loop_item("COLUMN".$i."WIDGETS");
            $this->addWidgetToEditable($template,"COLUMN".$i."WIDGETS",$widget,$index,$pos);
            $pos++;
          }
        }
        $i++;
      }
      $hiddenwidgets = $this->getHiddenWidgets();
      $i = 0;
      if($hiddenwidgets){
        foreach($hiddenwidgets as $widget){
            $index = $template->add_loop_item("HIDDENWIDGETS");
            $this->addWidgetToEditable($template,"HIDDENWIDGETS",$widget,$index,$i);
            $i++;
        }
      }
      $i = 0;
      if($allwidgets){
        foreach($allwidgets as $widget){
          $addItem = !$this->usedwidgets;
          if(!$addItem) $addItem = !in_array($widget->path,$this->usedwidgets);
          if($addItem){
            $widget->load();
            $index = $template->add_loop_item("DONTUSEDWIDGETS");
            $this->addWidgetToEditable($template,"DONTUSEDWIDGETS",$widget,$index,$i);
            $i++;
          }
        }
      }
      return $template->getCode();
    }

    /**
     *
     * @param Template $template
     * @param string $column
     * @param WidgetBase $widget
     * @param int $index
     * @param int $position
     * @return Template 
     */
    private function addWidgetToEditable(Template $template,$column,WidgetBase $widget,$index,$position){
      $template->assign_loop_var($column,$index,"WIDGETNAME",$widget->headline);
      $template->assign_loop_var($column,$index,"WIDGETPATH",htmlentities(str_replace(".","_",$widget->path)));
      $template->assign_loop_var($column,$index,"PLACE",$column."|".$position);
      $this->usedwidgets[] = $widget->path;
      return $template;
    }
    
    /**
     *
     * @param Page $newPage
     * @param Page $oldPage 
     */
    public function save(Page $newPage,Page $oldPage){
    }
    
    /**
     *
     * @param int $id
     * @return string 
     */
    function getColumnCode($id){
      $res = '<ul id="column';
      $res .= $id-1;
      $res .= '" class="column">';
      if(isset($this->cols[$id])){
        foreach($this->cols[$id] as $widget){
          $widget->displayType = "dashboard";
          $res .= $widget->getCode();
        }
      }
      $res .= "</ul>";
      return $res;
    }
    
    function displayColumn($id){
      echo $this->getColumnCode($id);
    }

    /**
     *
     * @return array 
     */
    function getHiddenWidgets(){
      $widgets = DataBase::Current()->ReadRows("SELECT class,{'dbprefix'}dashboards.path FROM {'dbprefix'}dashboards INNER JOIN {'dbprefix'}widgets ON {'dbprefix'}dashboards.path = {'dbprefix'}widgets.path WHERE alias = '".DataBase::Current()->EscapeString($this->page->alias)."' AND col = '0'");
      if($widgets){
        foreach($widgets as $widget){
          $widget = WidgetController::getWidget($widget);
          $widget->load();
          $res[] = $widget;
        }
      }
      return $res;
    }

    public function delete(){
      $dashboard = DataBase::Current()->EscapeString($this->page->alias);
      DataBase::Current()->Execute("DELETE FROM {'dbprefix'}dashboards WHERE alias = '".$dashboard."'");
    }

    function displayBreadcrumb($separator,$class,$idpraefix){
      $host = Settings::getInstance()->get("host");
      ?>
        <script type="text/javascript" src="<?PHP echo $host; ?>/system/skins/backenddefault/breadcrumb.js"></script>
        <ul id="breadcrumb_dropdown">
          <li>
            <?PHP
              $i = 1;
              $breadcrumb = $this->page->getBreadcrumb();
              while($i <= count($breadcrumb)){
                $url = UrlRewriting::GetUrlByAlias($breadcrumb[$i-1][0]);
                echo "<a style='display:inline' href=\"".$url."\" class=\"".$class."\" 
                      id=\"".$idpraefix.$i."\">".$breadcrumb[$i-1][1]."</a>";
                if($i < count($breadcrumb)){
                  echo $separator;
                }
                $i++;
              }
              if(isset($_GET['dir']) && substr($_GET['dir'],0,1) != '.'){
                $_SESSION['dir'] = $_GET['dir'];
                $first = true;
                $fulldir = "";
                foreach(explode('/',$_GET['dir']) as $dir){
                  if(!$first){
                    echo $separator." ";
                    $fulldir .= "/".$dir;
                  }
                  else{
                    $first = false;
                    $fulldir .= $dir;
                  }
                  $url = UrlRewriting::GetUrlByPage($this->page,"dir=".$fulldir);
                  echo "<a style='display:inline' href='".$url."'>".$dir."</a>";
                }
              }
              else{
                $_SESSION['dir'] = "";
              }
              if($_SESSION['dir'] == "/"){
                $_SESSION['dir'] = "";
              }
			  if(!isset($_GET['dir'])){
				$_GET['dir'] = "/";
			  }
              $subFolders = FileServer::getFolders(Settings::getInstance()->get("root")."content/articles/".$_GET['dir']);
              sort($subFolders);
              $host = Settings::getInstance()->get("host");
              if($subFolders){
            ?>
          </li>
          <li>
            <a href="#" onmouseover="openFolders()" onmouseout="closeFoldersTime()">-&gt; </a>
            <div id="subfolders" onmouseover="cancelClosingFolders()" onmouseout="closeFoldersTime()">
              <?PHP
                foreach($subFolders as $folder){
                  $url = UrlRewriting::GetUrlByPage($this->page,"dir=".$_GET['dir']."/".$folder);
                  echo "<a href='".$url."'>".$folder."</a>";
                }
              ?>
            </div>
          </li>
        </ul>
      <?PHP
      }
    }
  }
?>